# -*- coding: utf-8 -*-
"""
 Created by wq.wang on 2017/12/22
"""
import logging

from django.conf import settings
from django.conf.urls.static import static
from django.http import JsonResponse

try:
    from django.urls import path
except Exception:
    from django.conf.urls import url as path

from wserver.base.server import WServer
from wserver.base.service import SERVICE

_logger = logging.getLogger(__name__)


class DjangoWServer(WServer):
    def __init__(self, load_module='service', base_url='/', description="", version='', title="", teamOfService="") -> None:
        self.base_url = base_url
        self.description = description
        self.version = version
        self.title = title
        self.teamOfService = teamOfService
        install_apps = settings.INSTALLED_APPS
        mods = ["%s.%s" % (install_app, load_module) for install_app in install_apps if
                not install_app.startswith("django")]

        super().__init__(mods, True)

    def get_swagger(self, request, *args, **kwargs):
        hostname = request.get_host()
        swagger = self.get_swagger_doc(hostname, self.base_url, self.description, self.version, self.title,
                                       self.teamOfService)
        return JsonResponse(swagger)

    def get_url(self):
        urls = []
        for service in SERVICE.values():
            urls.extend(service.gen_route(base_url=self.base_url))
        urls.append(path('swagger.json', self.get_swagger))
        return urls + static("/doc", document_root=self._default_static_doc)
